package com.example.foodwebbackend.controller;

import com.example.foodwebbackend.dto.ApiResponse;
import com.example.foodwebbackend.dto.MerchantFoodDto;
import com.example.foodwebbackend.entity.MerchantFood;
import com.example.foodwebbackend.service.MerchantFoodService;
import com.example.foodwebbackend.service.UserRatingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/food")
@CrossOrigin(origins = "*")
public class FoodController {

    @Autowired
    private MerchantFoodService merchantFoodService;
    
    @Autowired
    private UserRatingService userRatingService;

    /**
     * 获取菜品详情
     */
    @GetMapping("/{foodId}")
    public ApiResponse<Map<String, Object>> getFoodDetail(@PathVariable Integer foodId) {
        try {
            MerchantFood food = merchantFoodService.getFoodById(foodId);
            if (food == null) {
                return ApiResponse.error("菜品不存在");
            }
            
            // 初始化评分数据为0，如果获取评价失败也不影响基本信息显示
            double avgRating = 0.0;
            int totalReviews = 0;
            
            try {
                // 计算真实的评分数据
                List<Map<String, Object>> reviews = userRatingService.getFoodReviews(foodId);
                totalReviews = reviews.size();
                
                if (totalReviews > 0) {
                    double sum = 0.0;
                                    for (Map<String, Object> review : reviews) {
                    Object ratingObj = review.get("rating");
                    if (ratingObj != null) {
                        // 处理BigDecimal类型的rating
                        if (ratingObj instanceof java.math.BigDecimal) {
                            sum += ((java.math.BigDecimal) ratingObj).doubleValue();
                        } else if (ratingObj instanceof Integer) {
                            sum += (Integer) ratingObj;
                        } else if (ratingObj instanceof Double) {
                            sum += (Double) ratingObj;
                        }
                    }
                }
                    avgRating = sum / totalReviews;
                    // 保留一位小数
                    avgRating = Math.round(avgRating * 10.0) / 10.0;
                }
            } catch (Exception e) {
                // 如果获取评价失败，使用默认值0，不影响基本信息显示
                System.err.println("获取评价数据失败: " + e.getMessage());
            }
            
            // 转换为前端需要的格式
            Map<String, Object> result = new HashMap<>();
            result.put("foodId", food.getFoodId());
            result.put("merchantId", food.getMerchantId());
            result.put("foodName", food.getFoodName());
            result.put("foodDescription", food.getFoodDescription());
            result.put("foodImagePath", food.getFoodImagePath());
            result.put("categoryId", food.getCategoryId());
            result.put("foodPrice", food.getPrice());
            result.put("foodRating", avgRating);  // 使用计算出的真实评分
            result.put("totalReviews", totalReviews);  // 使用计算出的真实评论数
            result.put("merchantName", food.getMerchantName());
            result.put("categoryName", food.getCategoryName());
            result.put("merchantAddress", food.getMerchantAddress());  // 添加餐厅地址
            result.put("contactPhone", food.getContactPhone());  // 添加联系电话
            result.put("createdTime", food.getCreatedTime());
            result.put("updatedTime", food.getUpdatedTime());
            result.put("isActive", food.getIsActive());
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            e.printStackTrace();  // 打印详细错误信息
            return ApiResponse.error("获取菜品详情失败: " + e.getMessage());
        }
    }

    /**
     * 获取菜品评价
     */
    @GetMapping("/{foodId}/reviews")
    public ApiResponse<Map<String, Object>> getFoodReviews(@PathVariable Integer foodId) {
        try {
            // 获取菜品的所有评价
            List<Map<String, Object>> reviews = userRatingService.getFoodReviews(foodId);
            
            // 计算评分分布
            Map<String, Object> distribution = new HashMap<>();
            distribution.put("5", 0);
            distribution.put("4", 0);
            distribution.put("3", 0);
            distribution.put("2", 0);
            distribution.put("1", 0);
            
            for (Map<String, Object> review : reviews) {
                Object ratingObj = review.get("rating");
                if (ratingObj != null) {
                    int rating = 0;
                    // 处理BigDecimal类型的rating
                    if (ratingObj instanceof java.math.BigDecimal) {
                        rating = ((java.math.BigDecimal) ratingObj).intValue();
                    } else if (ratingObj instanceof Integer) {
                        rating = (Integer) ratingObj;
                    } else if (ratingObj instanceof Double) {
                        rating = ((Double) ratingObj).intValue();
                    }
                    
                    if (rating >= 1 && rating <= 5) {
                        distribution.put(String.valueOf(rating), 
                            (Integer) distribution.get(String.valueOf(rating)) + 1);
                    }
                }
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("reviews", reviews);
            result.put("distribution", distribution);
            
            return ApiResponse.success(result);
        } catch (Exception e) {
            return ApiResponse.error("获取评价失败: " + e.getMessage());
        }
    }
} 